# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

import json
import sys
from typing import List, Literal, TypedDict

import stringcase

strings_json, outfile = sys.argv[1:]
modules = json.load(open(strings_json, encoding="utf8"))


class Variable(TypedDict):
    name: str
    kind: Literal["Any", "Int", "String", "Float"]


def legacy_enum() -> str:
    out = ["class LegacyTranslationEnum:"]
    for module in modules:
        for translation in module["translations"]:
            key = stringcase.constcase(translation["key"])
            value = f'({module["index"]}, {translation["index"]})'
            out.append(f"    {key} = {value}")

    return "\n".join(out) + "\n"


def methods() -> str:
    out = [
        "class GeneratedTranslations:",
        "    def _translate(self, module: int, translation: int, args: Dict) -> str:",
        "        raise Exception('not implemented')",
    ]
    for module in modules:
        for translation in module["translations"]:
            key = translation["key"].replace("-", "_")
            arg_types = get_arg_types(translation["variables"])
            args = get_args(translation["variables"])
            doc = translation["text"]
            out.append(
                f"""
    def {key}(self, {arg_types}) -> str:
        r''' {doc} '''
        return self._translate({module["index"]}, {translation["index"]}, {{{args}}})
"""
            )

    return "\n".join(out) + "\n"


def get_arg_types(args: List[Variable]) -> str:

    return ", ".join(
        [f"{stringcase.snakecase(arg['name'])}: {arg_kind(arg)}" for arg in args]
    )


def arg_kind(arg: Variable) -> str:
    if arg["kind"] == "Int":
        return "int"
    elif arg["kind"] == "Any":
        return "FluentVariable"
    elif arg["kind"] == "Float":
        return "float"
    else:
        return "str"


def get_args(args: List[Variable]) -> str:
    return ", ".join(
        [f'"{arg["name"]}": {stringcase.snakecase(arg["name"])}' for arg in args]
    )


out = ""

out += legacy_enum()
out += methods()


open(outfile, "wb").write(
    (
        '''# Copyright: Ankitects Pty Ltd and contributors
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
# pylint: skip-file

from __future__ import annotations

"""
This file is automatically generated from the *.ftl files.
"""
    
import enum
from typing import Dict, Union

FluentVariable = Union[str, int, float]

'''
        + out
    ).encode("utf8")
)
